package ar.com.ford.it.fullEconomics.interfaces.strategys;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import org.apache.commons.lang.StringUtils;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.interfaces.interfaz.InterfaceProccesFile;
import ar.com.ford.it.fullEconomics.logic.PricingLogic;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesm01Currency;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp04Supply;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp05Pricing;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx03Intflog;
import ar.com.ford.it.fullEconomics.struct.CounterStruct;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;
import cobolConversion.EbcdicString;
import cobolConversion.EbcdicTable;

//import ar.com.ford.it.fullEconomics.interfaces.strategys.PackedDecimalConverter;

public class PriceStrategy implements InterfaceProccesFile {

	private EbcdicTable ebcdicTable = new EbcdicTable();
	
    public String getHeaderDescription(Object aLine) {
        byte[] myBufferRead = (byte[]) aLine;
        String msg = null;
        String line = new EbcdicString(ebcdicTable, myBufferRead).toString()
                .toString();
        msg = "Id de archivo :" + line.toString().substring(12, 43).trim()
                + "Fecha de descarga " + line.substring(50, 52) + "/"
                + line.substring(48, 50) + "/" + line.substring(44, 48);
        return msg;
    }

    public String getTrailerDescription(Object aLine) {
        byte[] myBufferRead = (byte[]) aLine;
        String msg = null;
        String line = new EbcdicString(ebcdicTable, myBufferRead).toString()
                .toString();
        String file = line.toString().substring(12, 44);
        String recCountPrice = Integer.valueOf(line.toString().substring(56, 65)).toString();
        String recCountRemarks = Integer.valueOf(line.toString().substring(65, 74)).toString();
        String recCountNonStd = Integer.valueOf(line.toString().substring(74, 83)).toString();
        
        int recCount = Integer.valueOf(recCountPrice) + Integer.valueOf(recCountRemarks) + Integer.valueOf(recCountNonStd);
        
        msg = " Nombre de archivo: " + file + " Fecha de Creacion:"
                + line.substring(50, 52) + "/" + line.substring(48, 50) + "/"
                + line.substring(44, 48) + " Cantidad de registros:" + recCount
                + " - " + recCountPrice + " prices, " + recCountRemarks 
                + " remarks, " + recCountNonStd + " non-std records";

        return msg;
    }
    
    public Integer getRecordCount(Object aLine){
        byte[] myBufferRead = (byte[]) aLine;
        String line = new EbcdicString(ebcdicTable, myBufferRead).toString()
                .toString();
        
        String recCountPrice = Integer.valueOf(line.toString().substring(56, 65)).toString();
        String recCountRemarks = Integer.valueOf(line.toString().substring(65, 74)).toString();
        String recCountNonStd = Integer.valueOf(line.toString().substring(74, 83)).toString();
        
        int recCount = Integer.valueOf(recCountPrice) + Integer.valueOf(recCountRemarks) + Integer.valueOf(recCountNonStd);
        
        return recCount;
    }

    public CounterStruct insertData(Collection data, String userId,
                           Teesx03Intflog logNumber)
            throws FullEconomicsException {
        PricingLogic logic = new PricingLogic();
        CounterStruct counter = logic.insertCepsPrices((Collection<Teesp05Pricing>) data, userId,
                logNumber);
        return counter;
    }

    public void processLine(Object aLine, String userId, Collection data)
            throws FullEconomicsException {

        byte[] myBufferRead = (byte[]) aLine;
        String line = new EbcdicString(ebcdicTable, myBufferRead).toString();
        System.out.println("line es:\n" + line);
        if (getAsciis(myBufferRead,73,4).equals("020")) {
                   	
            String plantAltCodeC = getAsciis(myBufferRead,49,3);
            String partPrefixCodeC = getAsciis(myBufferRead,51,7).trim();
            if (partPrefixCodeC == "") partPrefixCodeC = " ";
            String partBaseCodeC = getAsciis(myBufferRead,57,9).trim();
            if (partBaseCodeC == "") partBaseCodeC = " ";
            String partSuffixCodeC = getAsciis(myBufferRead,65,9).trim();
            if (partSuffixCodeC == "") partSuffixCodeC = " ";
            String supplierCodeC = getAsciis(myBufferRead,39,6).trim();

            String anio = getAsciis(myBufferRead,76,5);
            String mes  = getAsciis(myBufferRead,80,3);
            String dia  = getAsciis(myBufferRead,82,3); 
            String priceEffectiveDateY = dia + "/" + mes + "/" + anio;
            
            anio = getAsciis(myBufferRead,92,5);
            mes = getAsciis(myBufferRead,96,3);
            dia = getAsciis(myBufferRead,98,3);
            String priceEndDateY = dia + "/" + mes + "/" + anio;
            if (priceEndDateY.equalsIgnoreCase("99/99/9999")) 
            	priceEndDateY = "31/12/9999";
            
            String priceAmountA = "0";
            try {
                double nPrice = parsePackedDecimal(myBufferRead,153,7,6);
                System.out.println("Precio@153:"+nPrice);
                //double Precio2 = parsePackedDecimal(myBufferRead,153,7,5);
                priceAmountA = Double.toString(nPrice);
			} catch (Exception e) {
				System.out.println("Error en parsePackedDecimal()");
			}
                        
            /*String priceAmountA = new PackedDecimal(myBufferRead,153,8,5).toString();
            String spriceAmountA  = getAsciis(myBufferRead,153,7); 
            */
            
            String currencyCodeC = getAsciis(myBufferRead,129,4);
            String supplySharePercentP = getAsciis(myBufferRead,160,4).trim(); 
            if (StringUtils.isBlank(supplySharePercentP)) supplySharePercentP = "0";

            String sLineaBorrar = 
            	plantAltCodeC + "-" + "F" +
            	partPrefixCodeC + "-" +
            	partBaseCodeC + "-" +
            	partSuffixCodeC + "-- GSDB:" +
            	supplierCodeC + " from:" +
            	priceEffectiveDateY + " to " +
            	priceEndDateY + " --> Price:" +
            	priceAmountA + " " +
            	currencyCodeC + " - " +
            	supplySharePercentP + "%";
            
            System.out.println(sLineaBorrar);
            
            Teesp05Pricing pricing = new Teesp05Pricing();
            Teesp04Supply supply = new Teesp04Supply();
            Teesp01Part part = new Teesp01Part();
            Teess01Supplier supplier = new Teess01Supplier();
            Teesg01Plant plant = new Teesg01Plant();
            Teesm01Currency currency = new Teesm01Currency();

            // Plant
            plant.setEesg01PlantAlternateCodeC(plantAltCodeC);
            
            // Currency
            currency.setEesm01CurrencyCodeC(currencyCodeC);
            
            // Pieza
            part.setEesp01PlantCodeC(plant);
            part.setEesp01PartClassCodeC("F");
            part.setEesp01PartPrefixCodeC(partPrefixCodeC);
            part.setEesp01PartBaseCodeC(partBaseCodeC);
            part.setEesp01PartSuffixCodeC(partSuffixCodeC);
            
            // supplier
            supplier.setEess01PlantCodeC(plant);
            supplier.setEess01SupplierClassCodeC("F");
            supplier.setEess01SupplierCodeC(supplierCodeC);
            supplier.setEess01SupplierNameN("Supplier GSDB: " + supplierCodeC );

            // supply
            supply.setEesp04PlantCodeC(plant);
            supply.setTeesp01Part(part);
            supply.setTeess01Supplier(supplier);
            if (StringUtils.isBlank(supplySharePercentP))
                supply.setEesp04SupplySharePercentP(new BigDecimal(0));
            else
            {
            	//System.out.println("line.substring(160, 163) es:" + line.substring(160, 163) );
        	    //System.out.println("EbcdicString es:" + getAsciis(myBufferRead,160,4));
                supply.setEesp04SupplySharePercentP(new BigDecimal(supplySharePercentP));
            }
            
            // Pricing
            pricing.setEesp05PlantCodeC(plant);
            pricing.setTeesp04Supply(supply);
            pricing.setEesp05CurrencyCodeC(currency);
            pricing.setEesp05PriceEffectiveDateY(new Timestamp(
                    FullEconomicsDateUtil.format(priceEffectiveDateY).getTimeInMillis()));
                        
            Calendar endDate = FullEconomicsDateUtil.format(priceEndDateY);
            if (endDate == null)
                pricing.setEesp05PriceEndDateY(FullEconomicsDateUtil.maxDate());
            else
                pricing.setEesp05PriceEndDateY(new Timestamp(endDate
                        .getTimeInMillis()));

            pricing.setEesp05PriceAmountA(new BigDecimal(priceAmountA).multiply(new BigDecimal(10)));
            
            data.add(pricing);
            
        }
    }

    public boolean validateHeaderAndTrailer(Object line) {
        byte[] myBufferRead = (byte[]) line;
        EbcdicTable ebcdicTable = new EbcdicTable();
        ebcdicTable.set_pageCode(EbcdicTable.ASCII_USA_00437);
        EbcdicString ebcdicString = new EbcdicString(ebcdicTable, myBufferRead);
        
        System.out.println("EvalHeadTrail -->>" + ebcdicString.toString().toString());
                
        String sHeaderMatch = new EbcdicString(ebcdicTable, myBufferRead, 12, 29).toString().toString().trim();
        String sTrailerMatch = new EbcdicString(ebcdicTable, myBufferRead, 12, 27).toString().toString().trim();
				
		System.out.println("Header: "+sHeaderMatch);
		System.out.println("Trailer: "+sTrailerMatch);
        
        if (sTrailerMatch.equalsIgnoreCase("END OF ARGENTINA CEPS FILE")
                || sHeaderMatch.equalsIgnoreCase("START OF ARGENTINA CEPS FILE")) {
            return false;
        } else {
            return true;
        }
    }

    public boolean validateRecordCount(int trailerRecordCount, int lineCount, int dataSize) {
        //if( trailerRecordCount == dataSize)
    	// trailerRecordCount + 1 line Header + 1 line Trailer
    	if((trailerRecordCount + 2 == lineCount) && (dataSize <= trailerRecordCount))
            return true;
        return false;
    }
    
    private String getAsciis(byte[] myBufferRead ,int curpos ,int size)
    {
    	return new EbcdicString(ebcdicTable, myBufferRead,curpos,size).toString(); 
    }
    
    public static double parsePackedDecimal(byte[] pdIn, int offset, int len, int decDigits) throws Exception {   
//    	 Convert packed decimal to long   
    	      final int PlusSign = 0x0C;       // Plus sign   
    	      final int MinusSign = 0x0D;      // Minus   
    	      final int NoSign = 0x0F;         // Unsigned   
    	      final int DropHO = 0xFF;         // AND mask to drop HO sign bits   
    	      final int GetLO  = 0x0F;         // Get only LO digit   
    	long val = 0;                    // Value to return    
    	    
    	      for(int i=offset; i < offset+len; i++) {   
    	         int aByte = pdIn[i] & DropHO; // Get next 2 digits & drop sign bits   
    	         if(i == offset+len - 1) {    // last digit?   
    	            int digit = aByte >> 4;    // First get digit   
    	            val = val*10 + digit;   
    	            //System.out.println("digit=" + digit + ", val=" + val);   
    	            int sign = aByte & GetLO;  // now get sign   
    	            if (sign == MinusSign)   
    	               val = -val;   
    	            else {   
    	               // Do we care if there is an invalid sign?   
    	               if(sign != PlusSign && sign != NoSign)   
    	                  throw new Exception("OC7");   
    	            }   
    	         }else {   
    	            int digit = aByte >> 4;    // HO first      
    	            val = val*10 + digit;   
    	            //System.out.println("digit=" + digit + ", val=" + val);   
    	            digit = aByte & GetLO;      // now LO   
    	            val = val*10 + digit;   
    	            //System.out.println("digit=" + digit + ", val=" + val);   
    	         }   
    	      }
    	      
    	double retValue = 0;       
    	if (decDigits > 0) {  
    		double divisor = Math.pow(10,decDigits); 
    	    retValue = val / divisor;
    	} else {
    		retValue = val;
    	}
    	            
    	return retValue;   
    	} // end parse()   


}
